// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.ShipPlansSub;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.LogisticsChannelMapper;
import com.fowo.api.mapper.LogisticsProviderMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShipPlansSubMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.listing.father.ListingFatherItemVo;
import com.fowo.api.model.listing.father.ListingFatherSearchParamPo;
import com.fowo.api.model.logistics.channel.LogisticsChannelItemVo;
import com.fowo.api.model.logistics.channel.LogisticsChannelSearchParamPo;
import com.fowo.api.model.logistics.provider.LogisticsProviderItemVo;
import com.fowo.api.model.logistics.provider.LogisticsProviderSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubExcelPo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubImportPo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubItemVo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubItemVoPages;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubRelateShipmentListParam;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubRelateShipmentListResult;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubSearchParamPo;
import com.fowo.api.model.ship.plans.sub.ShipPlansSubVo;
import com.fowo.api.model.ship.plans.sub.constant.ShipPlansSubGenerateshipmentEnums;
import com.fowo.api.model.ship.plans.sub.constant.ShipPlansSubStateEnums;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.service.ShipPlansSubService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发货计划单子表 服务实现基类
 * @author 蜂窝蜜造平台 配置人：杨志贤，王阳阳
 */
@Slf4j
@DataObjectType(ShipPlansSub.class)
@DS("ds24")
public class ShipPlansSubBaseServiceImpl
  extends ServiceImpl<ShipPlansSubMapper, ShipPlansSub>
  implements ShipPlansSubService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("parentShipPlansCreateBatchNumber", "sp.`create_batch_number`");
      put("productIdName", "p.`name`");
      put("shopIdShopName", "si.`shop_name`");
      put("logisticsBusinessIdName", "lp.`name`");
      put("logisticsChannelName", "lc.`name`");
      put("deliveryWarehouseIdName", "w.`name`");
      put("deliveryWarehouseStoreIdShopName", "si2.`shop_name`");
      put("deliveryWarehouseStoreFnskuFnsku", "lf.`fnsku`");
      put("lockBinStorageBin", "wb.`storage_bin`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ShipPlansSubService self;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected LogisticsProviderMapper logisticsProviderMapper;

  @Resource
  protected LogisticsChannelMapper logisticsChannelMapper;

  @Resource
  protected ListingFatherMapper listingFatherMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected WarehouseBinMapper warehouseBinMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  protected Validator validator;

  /**
   * 创建发货计划单子表
   * @param model 发货计划单子表
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ShipPlansSubVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlansSub entity = new ShipPlansSub();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getState() == null) {
      entity.setState("0");
    }

    if (model.getIsLock() == null) {
      entity.setIsLock(false);
    }

    if (model.getIsUrgent() == null) {
      entity.setIsUrgent(false);
    }

    if (model.getPlanNumHidden() == null) {
      entity.setPlanNumHidden(1);
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "ShipPlansSub.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("发货计划单子表保存失败");
  }

  /**
   * 批量更新 发货计划单 下属数据
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void saveAllByParentShipPlans(
    Long parentShipPlans,
    List<ShipPlansSubItemVo> list
  ) throws Exception {
    for (ShipPlansSubItemVo itemVo : list) {
      if (
        itemVo.getId() != null &&
        itemVo.getDelFlag() != null &&
        itemVo.getDelFlag()
      ) {
        // 删除处理
        this.delete(itemVo.getId());
        continue;
      }
      ShipPlansSub item = new ShipPlansSub();
      BeanUtils.copyProperties(itemVo, item);
      if (item.getParentShipPlans() == null) {
        item.setId(null);
        item.setParentShipPlans(parentShipPlans);
      }
      if (item.getId() == null) {
        this.save(item);
      } else {
        this.updateById(item);
      }
    }
  }

  /**
   * 返回 发货计划单 下属多级分页
   */
  @Override
  public Map<String, Page<ShipPlansSubItemVoPages>> pagesByParentShipPlans(
    ShipPlansSubSearchParamPo search
  ) {
    search.setDisableDataPremissions(true);
    List<ShipPlansSubItemVoPages> listMap =
      baseMapper.selectPagesByParentShipPlans(search);
    Map<Long, List<ShipPlansSubItemVoPages>> pageMap = listMap
      .stream()
      .collect(
        Collectors.groupingBy(ShipPlansSubItemVoPages::getParentShipPlans)
      );
    Map<String, Page<ShipPlansSubItemVoPages>> result = new HashMap<>();
    for (Map.Entry<Long, List<ShipPlansSubItemVoPages>> listEntry : pageMap.entrySet()) {
      Page<ShipPlansSubItemVoPages> page = new Page<>(
        1,
        search.getPageSize(),
        listEntry.getValue().get(0).getPartRows()
      );
      page.setRecords(listEntry.getValue());
      result.put(listEntry.getKey().toString(), page);
    }
    return result;
  }

  /**
   * 更新发货计划单子表
   * @param model 发货计划单子表
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ShipPlansSubVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlansSub entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货计划单子表不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "orderSn",
      "msku",
      "fnsku",
      "asin",
      "parentasin",
      "shopId",
      "totalShipment",
      "differenceQuantity",
      "estimatedTimeOfArrival",
      "state",
      "estimatedTimeOfLogistics",
      "fbaForecastingInventoryTechnique",
      "quantityAvailable",
      "quantityTest",
      "quantityAog",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新发货计划单子表（带空值）
   * @param model 发货计划单子表
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ShipPlansSubVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    ShipPlansSub entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("发货计划单子表不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(ShipPlansSub::getParentShipPlans, model.getParentShipPlans())
      .set(
        model.getImg() != null,
        ShipPlansSub::getImg,
        JSON.toJSONString(model.getImg())
      )
      .setSql(model.getImg() == null, "img = null")
      .set(ShipPlansSub::getProductId, model.getProductId())
      .set(ShipPlansSub::getSku, model.getSku())
      .set(ShipPlansSub::getPlannedShipment, model.getPlannedShipment())
      .set(ShipPlansSub::getTypeOfShipping, model.getTypeOfShipping())
      .set(ShipPlansSub::getLogisticsBusinessId, model.getLogisticsBusinessId())
      .set(ShipPlansSub::getLogisticsChannel, model.getLogisticsChannel())
      .set(ShipPlansSub::getDeliveryWarehouseId, model.getDeliveryWarehouseId())
      .set(ShipPlansSub::getPackagingType, model.getPackagingType())
      .set(ShipPlansSub::getRemarks, model.getRemarks())
      .set(ShipPlansSub::getPerCarton, model.getPerCarton())
      .set(ShipPlansSub::getCartonNumbers, model.getCartonNumbers())
      .set(
        ShipPlansSub::getScheduledDeliveryTime,
        model.getScheduledDeliveryTime()
      )
      .set(
        ShipPlansSub::getDeliveryWarehouseStoreId,
        model.getDeliveryWarehouseStoreId()
      )
      .set(
        ShipPlansSub::getDeliveryWarehouseStoreFnsku,
        model.getDeliveryWarehouseStoreFnsku()
      )
      .set(ShipPlansSub::getLastUpdateTime, model.getLastUpdateTime())
      .set(ShipPlansSub::getLastUpdateUser, model.getLastUpdateUser())
      .set(ShipPlansSub::getSpecifications, model.getSpecifications())
      .set(ShipPlansSub::getBoxgauge, model.getBoxgauge())
      .set(ShipPlansSub::getCbm, model.getCbm())
      .set(ShipPlansSub::getVolumeweight, model.getVolumeweight())
      .set(ShipPlansSub::getItemweight, model.getItemweight())
      .set(ShipPlansSub::getItemgrossweight, model.getItemgrossweight())
      .set(ShipPlansSub::getSingleitemweight, model.getSingleitemweight())
      .set(ShipPlansSub::getSingleboxweight, model.getSingleboxweight())
      .set(ShipPlansSub::getTotalweight, model.getTotalweight())
      .eq(ShipPlansSub::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ShipPlansSubSearchParamPo search) {
    return false;
  }

  /**
   * 删除发货计划单子表
   * @param id 发货计划单子表的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除发货计划单子表
   * @param ids 发货计划单子表的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ShipPlansSubImportPo> excelToImportRow(
    ShipPlansSubImportPo row,
    Integer rowNumber,
    ShipPlansSubVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ShipPlansSubImportPo> ir = new ImportRow<ShipPlansSubImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ShipPlansSubImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ShipPlansSubVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ShipPlansSubImportPo.class);

    // 一般数据处理
    vo.setPlannedShipment(SheetUtils.tryToLong(row.getPlannedShipment()));
    vo.setTotalShipment(SheetUtils.tryToLong(row.getTotalShipment()));
    vo.setDifferenceQuantity(SheetUtils.tryToLong(row.getDifferenceQuantity()));
    if (StringUtils.hasText(row.getTypeOfShipping())) {
      List<SysDictAllItem> typeOfShippingItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "typeOfShipping",
          n -> sysDictService.getDictItems("SCM00058")
        );
      ShipPlansSubVo finalVo = vo;
      typeOfShippingItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getTypeOfShipping()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setTypeOfShipping(i.getItemValue()),
          () ->
            ir.addError(
              "typeOfShipping",
              String.format(
                "必须为 %s 中之一",
                typeOfShippingItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setEstimatedTimeOfArrival(
      SheetUtils.tryToDate(row.getEstimatedTimeOfArrival())
    );
    SheetUtils.datePreviewFormat(
      row.getEstimatedTimeOfArrival(),
      row::setEstimatedTimeOfArrival
    );
    if (StringUtils.hasText(row.getPackagingType())) {
      List<SysDictAllItem> packagingTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "packagingType",
          n -> sysDictService.getDictItems("SCM00076")
        );
      ShipPlansSubVo finalVo = vo;
      packagingTypeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getPackagingType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setPackagingType(i.getItemValue()),
          () ->
            ir.addError(
              "packagingType",
              String.format(
                "必须为 %s 中之一",
                packagingTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getState())) {
      vo.setState(ShipPlansSubStateEnums.toValue(row.getState()));
      if (vo.getState() == null) {
        ir.addError("state", "状态只能是：“待处理”, “已处理”");
      }
    }
    vo.setPerCarton(SheetUtils.tryToInteger(row.getPerCarton()));
    vo.setCartonNumbers(SheetUtils.tryToInteger(row.getCartonNumbers()));
    vo.setScheduledDeliveryTime(
      SheetUtils.tryToDate(row.getScheduledDeliveryTime())
    );
    SheetUtils.datePreviewFormat(
      row.getScheduledDeliveryTime(),
      row::setScheduledDeliveryTime
    );
    vo.setFbaForecastingInventoryTechnique(
      SheetUtils.tryToInteger(row.getFbaForecastingInventoryTechnique())
    );
    vo.setQuantityAvailable(
      SheetUtils.tryToInteger(row.getQuantityAvailable())
    );
    vo.setQuantityTest(SheetUtils.tryToInteger(row.getQuantityTest()));
    vo.setQuantityAog(SheetUtils.tryToInteger(row.getQuantityAog()));
    vo.setIsLock(SheetUtils.tryToBoolean(row.getIsLock()));
    vo.setIsUrgent(SheetUtils.tryToBoolean(row.getIsUrgent()));
    vo.setShipmentNum(SheetUtils.tryToInteger(row.getShipmentNum()));
    vo.setDeliverNum(SheetUtils.tryToInteger(row.getDeliverNum()));
    vo.setPlanNumHidden(SheetUtils.tryToInteger(row.getPlanNumHidden()));
    vo.setCbm(SheetUtils.tryToDecimal(row.getCbm()));
    vo.setVolumeweight(SheetUtils.tryToDecimal(row.getVolumeweight()));
    vo.setItemweight(SheetUtils.tryToDecimal(row.getItemweight()));
    vo.setItemgrossweight(SheetUtils.tryToDecimal(row.getItemgrossweight()));
    vo.setSingleitemweight(SheetUtils.tryToDecimal(row.getSingleitemweight()));
    vo.setSingleboxweight(SheetUtils.tryToDecimal(row.getSingleboxweight()));
    vo.setTotalweight(SheetUtils.tryToDecimal(row.getTotalweight()));
    if (StringUtils.hasText(row.getGenerateshipment())) {
      vo.setGenerateshipment(
        ShipPlansSubGenerateshipmentEnums.toValue(row.getGenerateshipment())
      );
      if (vo.getGenerateshipment() == null) {
        ir.addError("generateshipment", "生成货件只能是：“否”, “是”");
      }
    }
    // 处理关联字段“产品”
    if (
      !SheetUtils.isBlank(row.getProductIdName()) &&
      SheetUtils.isBlank(row.getProductId())
    ) {
      ProductSearchParamPo productIdSearchParam = new ProductSearchParamPo();
      productIdSearchParam.setLimit(2); // 最大只返回二行记录
      productIdSearchParam.setNameEq(SheetUtils.trim(row.getProductIdName()));
      productIdSearchParam.applySqlSegments();
      List<ProductItemVo> productIdMatches = productMapper.search(
        productIdSearchParam
      );
      if (productIdMatches.size() == 0) {
        ir.addError("productIdName", "未能在产品管理中找到匹配的数据");
      } else if (productIdMatches.size() > 1) {
        ir.addError(
          "productIdName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setProductId(productIdMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", productIdMatches.get(0).getId())
          .put("fromObjectName", "ShipPlansSub")
          .put("fromObjectId", vo.getId())
          .put("fromField", "productId")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(2);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("img")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("picUrl")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("img")
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(productIdMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopIdShopName()) &&
      SheetUtils.isBlank(row.getShopId())
    ) {
      ShopInfoSearchParamPo shopIdSearchParam = new ShopInfoSearchParamPo();
      shopIdSearchParam.setLimit(2); // 最大只返回二行记录
      shopIdSearchParam.setShopNameEq(SheetUtils.trim(row.getShopIdShopName()));
      shopIdSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopIdMatches = shopInfoMapper.search(
        shopIdSearchParam
      );
      if (shopIdMatches.size() == 0) {
        ir.addError("shopIdShopName", "未能在店铺中找到匹配的数据");
      } else if (shopIdMatches.size() > 1) {
        ir.addError("shopIdShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShopId(shopIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getLogisticsBusinessIdName()) &&
      SheetUtils.isBlank(row.getLogisticsBusinessId())
    ) {
      LogisticsProviderSearchParamPo logisticsBusinessIdSearchParam =
        new LogisticsProviderSearchParamPo();
      logisticsBusinessIdSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsBusinessIdSearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsBusinessIdName())
      );
      logisticsBusinessIdSearchParam.applySqlSegments();
      List<LogisticsProviderItemVo> logisticsBusinessIdMatches =
        logisticsProviderMapper.search(logisticsBusinessIdSearchParam);
      if (logisticsBusinessIdMatches.size() == 0) {
        ir.addError("logisticsBusinessIdName", "未能在物流商中找到匹配的数据");
      } else if (logisticsBusinessIdMatches.size() > 1) {
        ir.addError(
          "logisticsBusinessIdName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsBusinessId(logisticsBusinessIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流渠道”
    if (
      !SheetUtils.isBlank(row.getLogisticsChannelName()) &&
      SheetUtils.isBlank(row.getLogisticsChannel())
    ) {
      LogisticsChannelSearchParamPo logisticsChannelSearchParam =
        new LogisticsChannelSearchParamPo();
      logisticsChannelSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsChannelSearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsChannelName())
      );
      logisticsChannelSearchParam.applySqlSegments();
      List<LogisticsChannelItemVo> logisticsChannelMatches =
        logisticsChannelMapper.search(logisticsChannelSearchParam);
      if (logisticsChannelMatches.size() == 0) {
        ir.addError("logisticsChannelName", "未能在物流渠道中找到匹配的数据");
      } else if (logisticsChannelMatches.size() > 1) {
        ir.addError(
          "logisticsChannelName",
          "关联不唯一，在物流渠道中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsChannel(logisticsChannelMatches.get(0).getId());
      }
    }
    // 处理关联字段“发货仓库店铺”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseStoreIdShopName()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouseStoreId())
    ) {
      ShopInfoSearchParamPo deliveryWarehouseStoreIdSearchParam =
        new ShopInfoSearchParamPo();
      deliveryWarehouseStoreIdSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseStoreIdSearchParam.setShopNameEq(
        SheetUtils.trim(row.getDeliveryWarehouseStoreIdShopName())
      );
      deliveryWarehouseStoreIdSearchParam.applySqlSegments();
      List<ShopInfoItemVo> deliveryWarehouseStoreIdMatches =
        shopInfoMapper.search(deliveryWarehouseStoreIdSearchParam);
      if (deliveryWarehouseStoreIdMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseStoreIdShopName",
          "未能在店铺中找到匹配的数据"
        );
      } else if (deliveryWarehouseStoreIdMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseStoreIdShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouseStoreId(
          deliveryWarehouseStoreIdMatches.get(0).getId()
        );
      }
    }
    // 处理关联字段“发货仓库FNSKU”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseStoreFnskuFnsku()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouseStoreFnsku())
    ) {
      ListingFatherSearchParamPo deliveryWarehouseStoreFnskuSearchParam =
        new ListingFatherSearchParamPo();
      deliveryWarehouseStoreFnskuSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseStoreFnskuSearchParam.setFnskuEq(
        SheetUtils.trim(row.getDeliveryWarehouseStoreFnskuFnsku())
      );
      deliveryWarehouseStoreFnskuSearchParam.applySqlSegments();
      List<ListingFatherItemVo> deliveryWarehouseStoreFnskuMatches =
        listingFatherMapper.search(deliveryWarehouseStoreFnskuSearchParam);
      if (deliveryWarehouseStoreFnskuMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseStoreFnskuFnsku",
          "未能在Listing中找到匹配的数据"
        );
      } else if (deliveryWarehouseStoreFnskuMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseStoreFnskuFnsku",
          "关联不唯一，在Listing中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouseStoreFnsku(
          deliveryWarehouseStoreFnskuMatches.get(0).getId()
        );
      }
    }
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseIdName()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouseId())
    ) {
      WarehouseSearchParamPo deliveryWarehouseIdSearchParam =
        new WarehouseSearchParamPo();
      deliveryWarehouseIdSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseIdSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliveryWarehouseIdName())
      );
      deliveryWarehouseIdSearchParam.setFinalFilters(new ArrayList<>());
      deliveryWarehouseIdSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      deliveryWarehouseIdSearchParam.applySqlSegments();
      List<WarehouseItemVo> deliveryWarehouseIdMatches = warehouseMapper.search(
        deliveryWarehouseIdSearchParam
      );
      if (deliveryWarehouseIdMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseIdName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (deliveryWarehouseIdMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseIdName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouseId(deliveryWarehouseIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“锁定仓位”
    if (
      !SheetUtils.isBlank(row.getLockBinStorageBin()) &&
      SheetUtils.isBlank(row.getLockBin())
    ) {
      WarehouseBinSearchParamPo lockBinSearchParam =
        new WarehouseBinSearchParamPo();
      lockBinSearchParam.setLimit(2); // 最大只返回二行记录
      lockBinSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getLockBinStorageBin())
      );
      lockBinSearchParam.setFinalFilters(new ArrayList<>());
      lockBinSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("parentWarehouse"))
            .setOp("eq")
            .setValue(SheetUtils.toString(vo.getDeliveryWarehouseId()))
        );
      lockBinSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> lockBinMatches = warehouseBinMapper.search(
        lockBinSearchParam
      );
      if (lockBinMatches.size() == 0) {
        ir.addError("lockBinStorageBin", "未能在仓位中找到匹配的数据");
      } else if (lockBinMatches.size() > 1) {
        ir.addError(
          "lockBinStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setLockBin(lockBinMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ShipPlansSubImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ShipPlansSubImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ShipPlansSubImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              ShipPlansSubImportPo row,
              AnalysisContext cxt
            ) {
              ShipPlansSubVo vo = new ShipPlansSubVo();
              ImportRow<ShipPlansSubImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ShipPlansSubImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ShipPlansSubImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ShipPlansSubVo vo = new ShipPlansSubVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"计划编号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "orderSn".equals(m.getField())
          )
      ) {
        vo.setOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "ShipPlansSub.orderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ShipPlansSubSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "parentShipPlans",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((ShipPlansSubItemVo) r).getParentShipPlansCreateBatchNumber()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ShipPlansSubItemVo) r).getProductIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shopId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ShipPlansSubItemVo) r).getShopIdShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "typeOfShipping",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00058")
      );
      exportOptions.addFieldMappingOption(
        "logisticsBusinessId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((ShipPlansSubItemVo) r).getLogisticsBusinessIdName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ShipPlansSubItemVo) r).getLogisticsChannelName())
          )
      );
      exportOptions.addFieldMappingOption(
        "estimatedTimeOfArrival",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "deliveryWarehouseId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((ShipPlansSubItemVo) r).getDeliveryWarehouseIdName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "packagingType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00076")
      );
      exportOptions.addFieldMappingOption(
        "state",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> ShipPlansSubStateEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "scheduledDeliveryTime",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addStringFields(
        "parentShipPlansCreateBatchNumber",
        "orderSn",
        "msku",
        "fnsku",
        "asin",
        "parentasin",
        "productIdName",
        "sku",
        "shopIdShopName",
        "typeOfShipping",
        "logisticsBusinessIdName",
        "logisticsChannelName",
        "deliveryWarehouseIdName",
        "packagingType",
        "remarks",
        "state",
        "isLock",
        "specifications",
        "boxgauge",
        "fnskuname",
        "title"
      );

      String fileName = String.format(
        "发货计划单子表(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeOfShippingItems = sysDictService.getDictItems(
      "SCM00058"
    );
    List<SysDictAllItem> packagingTypeItems = sysDictService.getDictItems(
      "SCM00076"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ShipPlansSubExcelPo> items = new ArrayList<ShipPlansSubExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ShipPlansSubItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ShipPlansSubItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ShipPlansSubItemVo item : list) {
        ShipPlansSubExcelPo excel = new ShipPlansSubExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getTypeOfShipping() != null) {
          typeOfShippingItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getTypeOfShipping()))
            .findFirst()
            .ifPresent(i -> excel.setTypeOfShipping(i.getItemText()));
        }
        if (item.getPackagingType() != null) {
          packagingTypeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getPackagingType()))
            .findFirst()
            .ifPresent(i -> excel.setPackagingType(i.getItemText()));
        }
        excel.setState(ShipPlansSubStateEnums.toLabel(item.getState()));
        if (item.getIsLock() != null) {
          excel.setIsLock(item.getIsLock() ? "是" : "否");
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "发货计划单子表(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ShipPlansSubExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过计划编号查询发货计划单子表主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderSn(String orderSn) {
    return this.baseMapper.getIdByOrderSn(orderSn);
  }

  /**
   * 通过计划编号查询发货计划单子表多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderSn(List<String> list) {
    return this.baseMapper.getIdsByOrderSn(list);
  }

  /**
   * 通过发货计划单子表主键查询计划编号
   */
  @Override
  public String getOrderSnById(Long id) {
    return this.baseMapper.getOrderSnById(id);
  }

  /**
   * 通过发货计划单子表主键查询计划编号列表
   */
  @Override
  public List<String> getOrderSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 发货计划单子表的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ShipPlansSubVo getVoById(Long id) throws Exception {
    ShipPlansSubVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询发货计划单子表
   * @param search 查询条件
   * @return 发货计划单子表分页查询结果
   */
  @Override
  public Page<ShipPlansSubItemVo> pageSearch(ShipPlansSubSearchParamPo search) {
    Page<ShipPlansSubItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ShipPlansSubItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 发货计划单子表快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ShipPlansSubOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ShipPlansSubItemVo>> searchOptions(
    ShipPlansSubSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询发货计划单子表
   * @param search 查询条件
   * @return 发货计划单子表列表查询结果
   */
  @Override
  public List<ShipPlansSubItemVo> search(ShipPlansSubSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询发货计划单子表最后更新时间
   * @param search 查询条件
   * @return 发货计划单子表最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ShipPlansSubSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 获取关联货件
   */
  @Override
  public ShipPlansSubRelateShipmentListResult relateShipmentList(
    ShipPlansSubRelateShipmentListParam param
  ) {
    return this.baseMapper.relateShipmentList(param);
  }
}
